﻿using System;
using System.Collections.Generic;
using System.Linq;
using EbbinghausWord.BLL;
using EbbinghausWord.Common;
using EbbinghausWord.Entities;

namespace EbbinghausWord.DAL
{
    /// <summary>
    /// 用户数据访问类
    /// </summary>
    public class UserDataDAL
    {
        #region private field
        private static SysDataContext _db = new SysDataContext();
        #endregion

        #region public method
        /// <summary>
        /// 创建或修改用户单词数据
        /// </summary>
        /// <param name="tableUserWordEntity"></param>
        public void EditOrCreate(TableUserWordEntity tableUserWordEntity)
        {
            var word = _db.TableUserWordEntities.FirstOrDefault(x => x.English == tableUserWordEntity.English);

            //如果不存在，则插入，否则编辑
            if (word == null)
            {
                _db.TableUserWordEntities.InsertOnSubmit(tableUserWordEntity);
            }
            else
            {
                word.IsInTheWordBook = tableUserWordEntity.IsInTheWordBook;
                word.LastRemeberingDateTime = tableUserWordEntity.LastRemeberingDateTime;
                word.NotRememberCounter = tableUserWordEntity.NotRememberCounter;
                word.RememberCounter = tableUserWordEntity.RememberCounter;
                word.RememberLevel = tableUserWordEntity.RememberLevel;
                word.RememberTimes = tableUserWordEntity.RememberTimes;
                word.StartRemeberingDateTime = tableUserWordEntity.StartRemeberingDateTime;
            }

            _db.SubmitChanges();
        }

        /// <summary>
        /// 获得当前词典的所有用户单词，数据库中没有的，用空白对象填充
        /// </summary>
        /// <returns></returns>
        public List<WordEntity> GetAllUserBook()
        {
            var et = new ExecuteTimer(false);
            var now = DateTime.Now;

            var bookEnglishList = new BookDAL().GetCurrentBookEnglishList();
            et.Show();

            var userWord = _db.TableUserWordEntities.ToList();
            et.Show();

            var words = bookEnglishList.GroupJoin(userWord, x => x, x => x.English,
                                      (x, y) => new { English = x, Word = y });
            
            //从数据库中查出用户单词数据
            var result = words.Where(x => x.Word.Any())
                .Select(x => WordEntity.FromTable(x.Word.First())).ToList();

            //填充空白对象
            result.AddRange(
                words.Where(x => !x.Word.Any()).Select(x => new WordEntity()
                                                                      {
                                                                          English = x.English,
                                                                          LastRemeberingDateTime = now,
                                                                          StartRemeberingDateTime = now,
                                                                      }).ToList());
            return result;
        }

        /// <summary>
        /// 当前的书籍中，是否存在需要复习的熟词
        /// </summary>
        /// <returns></returns>
        public bool IsHaveCompletedWordToReview()
        {
            var now = DateTime.Now;
            var duration = new UserConfig().CompletedWordReviewDuration * 7;
            var bookEnglishList = new BookDAL().GetCurrentBookEnglishList();
            var userWord = _db.TableUserWordEntities.Count(x => x.RememberLevel == SystemConfig.AchievementRememberLevel
                && x.LastRemeberingDateTime.Value.AddDays(duration) < now);

            return userWord != 0;
        }

        /// <summary>
        /// 当前的书籍中，是否存在需要复习的熟词
        /// </summary>
        /// <returns></returns>
        public List<WordEntity> GetCompletedWordToReview()
        {
            var et = new ExecuteTimer(false);

            var duration = new UserConfig().CompletedWordReviewDuration * 7;
            var deadline = DateTime.Now.AddDays(0 - duration);
            var completedLevel = SystemConfig.AchievementRememberLevel;

            et.Show("GetCurrentBookEnglishList");

            var userWord =
                _db.TableUserWordEntities.Where(x => x.RememberLevel == completedLevel
                                                     && x.LastRemeberingDateTime.Value < deadline)
                    .Select(WordEntity.FromTable).ToList();
            et.Show("Query");

            return userWord;
        }

        /// <summary>
        /// 清空学习记录
        /// </summary>
        public static void ClearDb()
        {
            foreach (var tableUserWordEntity in _db.TableUserWordEntities)
            {
                tableUserWordEntity.IsInTheWordBook = false;
                tableUserWordEntity.RememberLevel = 0;
                tableUserWordEntity.RememberTimes = 0;
            }

            _db.SubmitChanges();
        }

        #endregion
    }
}
